﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Modules.Commander.Comparers;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Caching;
using PmSoft.DBContext;
using PmSoft.Entity;
using PmSoft.Repositories;
using System.Reflection.Emit;

namespace Modules.Commander.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class CommanderProjectRepository : Repository<CommanderProject, DefaultDbContext>
    {
        private readonly ILogger logger;
        private readonly IApplicationContext applicationContext;
        private readonly static CommanderProjectComparer comparer = new();

        public CommanderProjectRepository(DefaultDbContext dbContext, IApplicationContext applicationContext, ILogger<CommanderProjectRepository> logger)
            : base(dbContext, applicationContext)
        {
            this.logger = logger;
            this.applicationContext = applicationContext;
        }

        public void CreateOrUpdate(int commanderId, IEnumerable<CommanderProject> inCommanderProjects)
        {
            var dbCommanderProjects = DbContext.Fetch<CommanderProject>("WHERE commander_id=@0", commanderId);
            var itemsToDelete = dbCommanderProjects.Except(inCommanderProjects, comparer).ToList();
            foreach (var item in itemsToDelete)
            {
                Delete(item);
            }
            var itemsToUpdate = dbCommanderProjects.Intersect(inCommanderProjects, comparer).ToList();
            foreach (var item in itemsToUpdate)
            {

            }
            var itemsToAdd = inCommanderProjects.Except(dbCommanderProjects, comparer).ToList();
            foreach (var item in itemsToAdd)
            {
                item.CommanderId = commanderId;
                Insert(item);
            }
        }

        public IEnumerable<CommanderProject> GetCommanderProjectsByCommanderId(int commanderId)
        {
            int areaVersion = EntityCacheService.GetAreaVersion("CommanderId", commanderId);
            return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
            {
                return $"CommanderProjectsByCommanderId:{commanderId}:{areaVersion}";
            }, () =>
            {
                Sql sql = Sql.Builder
                .Select("id")
                .From("commander_project")
                .Where("commander_id=@0", commanderId)
                .OrderBy("id");
                return sql;
            });
        }

        public bool ExistsCommanderProject(int projectId, int commanderId)
        {
            return DbContext.Exists<CommanderProject>("project_id=@0 AND commander_id=@1 ", projectId, commanderId);
        }
    }
}